/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package abricots.net.common;

import abricots.MyLog;
import com.esotericsoftware.minlog.Log;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 * @author charly
 */
public class AckedFramesManager {

    private final Map<Integer, Long> lastSentGameStates;
    private long lastAckedTime;
    private MyLog log = new MyLog(getClass().getSimpleName(), Log.LEVEL_DEBUG);

    public AckedFramesManager() {
        lastSentGameStates = Collections.synchronizedMap(new HashMap<Integer, Long>());
        lastAckedTime = -1;
    }

    public void newSentState(int paquetId, long time) {
        synchronized (lastSentGameStates) {
            lastSentGameStates.put(paquetId, time);
        }
        log.trace("New sent state with id " + paquetId + " for time " + time);
    }

    public void newAckedState(int paquetId) {
        synchronized (lastSentGameStates) {
            if (lastSentGameStates.isEmpty()
                    || paquetId == -1
                    || !lastSentGameStates.containsKey(paquetId)) {
                return;
            }
            log.trace("New acked state with paquetid " + paquetId);
            lastAckedTime = lastSentGameStates.get(paquetId);
            log.trace(" corresponding to gametime " + lastAckedTime);
            Iterator<Integer> it = lastSentGameStates.keySet().iterator();
            while (it.hasNext()) {
                int id = it.next();
                if (id <= paquetId) {
                    it.remove();
                    continue;
                }
            }
        }
    }

    public long getLastAckedTime() {
        return lastAckedTime;
    }
}
